import {
  JumpToMultiCheckOutParams,
  JumpToCheckOutParams,
  NavigateToNativeJoinMemberParams,
  NavigateToNativeDongDongGroupChatParams,
  NavigateToNativeDongDongChatByAndroidParams,
  NavigateToNativeDongDongChatByIosParams,
  NavigateToNativeLivePlayerRoomParams,
  NavigateToNativeShopIndexParams,
  NavigateToMiniProgramParams,
  NavigateToNativeProductDetailParams,
} from "./type";

type RequestIsvTokenOption = {
  url: string;
  id: string;
  success?: (res: any) => void;
  fail?: (e: any) => void;
};

type NavigateToNativeOption = {
  dataParam: {
    url: string;
    params: {
      category: string;
      url: string; //用接口返回的url
      des: string;
      param: Record<string, any>;
    };
  };
};

type AddJDReminderOption = {
  startDate: string;
  type: number;
  jumpStr: string;
  success?: (res: any) => void;
  fail?: (e: any) => void;
};

type jd = {
  requestIsvToken: (RequestIsvTokenOption: RequestIsvTokenOption) => Promise<number>;
  navigateToNative: (NavigateToNativeOption: NavigateToNativeOption) => void;
  addJDReminder: (AddJDReminderOption: AddJDReminderOption) => Promise<string>;
};

/**
 * @description 获取京东登录所需code
 */
export const requestIsvTokenSync = (params: Record<string, any>): Promise<string> => {
  return new Promise((resolve, reject) => {
    jd.requestIsvToken({
      ...params,
      success: res => {
        if (Object.prototype.toString.call(res) == "[object String]") {
          res = JSON.parse(res);
          resolve(res.data);
        } else if (Object.prototype.toString.call(res.token) == "[object Object]") {
          resolve(res.token.data);
        } else {
          resolve(res.token);
        }
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/**
 * 跳转多商品跳转下单页面（需申请权限）
 * 需注意：
 * 某些特殊商品类型目前暂不支持（如：全球购、预售等），具体类型可根据需求和使用场景进行反馈；
 * 某些商品类型（如：处方药、SCF天选等）需在高于一定的客户端版本下才支持；
 *  链接地址：https://joyspace.jd.com/page/0R1A4qsjlVbsUeDGdnik
 * @description 显示分享面板 (淘宝小程序独有)
 * @param {JumpToMultiCheckOutParams} params - 参数选项
 * @property {JumpToMultiCheckOutSkuInfos} params.skuInfos - 多商品数组[{ "skuId": "10030788332900", "num": 1 }]
 */

export const jumpToMultiCheckOutSync = (params: JumpToMultiCheckOutParams): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.jumpToMultiCheckOut({
      ...params,
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/**
 * @description 跳转JD小程序(新)
 * @param {ShowSharePanelOptions} params - 参数选项
 * @property {String} params.appId - 小程序Appid
 * @property {String} params.path - 小程序页面路径
 * @property {Object} params.extraData - 跳转额外传值参数
 */

export const navigateToMiniProgramSync = (params: NavigateToMiniProgramParams): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.navigateToMiniProgram({
      ...params,
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/**
 * @description 跳转到商品详情页
 * @param {ShowSharePanelOptions} params - 参数选项
 * @property {String||Number} params.skuId - 跳转商品skuId
 * @property {Object} params.param - 跳转携带参数
 */

export const navigateToNativeProductDetailSync = (params: NavigateToNativeProductDetailParams): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.navigateToNative({
      dataParam: {
        url: "openapp.jdmobile://virtual",
        params: {
          category: "jump",
          des: "productDetail",
          skuId: params.skuId,
          param: params.param,
        },
      },
      success: res => {
        resolve(res);
      },
      fail: res => {
        reject(res);
      },
    });
  });
};

/**
 * @description 跳转购物车（需申请权限）
 * @param {ShowSharePanelOptions} params - 参数选项
 */

export const routerToNativeCartSync = (): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.routerToNativeCart({
      success: res => {
        resolve(res);
      },
      fail: res => {
        reject(res);
      },
    });
  });
};

/**
 * @description 跳转到店铺主页
 * @param {ShowSharePanelOptions} params - 参数选项
 * @property {String||Number} params.shopId - 店铺shopId
 * @property {String||Numbe} params.venderId - venderId
 * @property {Object} params.param - 跳转携带参数
 *
 */

export const navigateToNativeShopIndex = async (params: NavigateToNativeShopIndexParams): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.navigateToNative({
      dataParam: {
        url: "openapp.jdmobile://virtual",
        params: {
          category: "jump",
          des: "jshopMain",
          shopId: params.shopId,
          venderId: params.venderId,
          param: {},
        },
      },
      success: res => {
        resolve(res);
      },
      fail: res => {
        reject(res);
      },
    });
  });
};

/**
 * 跳转商品跳转下单页面（需申请权限）
 * 需注意：
 * 某些特殊商品类型目前暂不支持（如：全球购、预售等），具体类型可根据需求和使用场景进行反馈；
 * 某些商品类型（如：处方药、SCF天选等）需在高于一定的客户端版本下才支持；
 *  链接地址：https://joyspace.jd.com/page/0R1A4qsjlVbsUeDGdnik
 * @description 跳转到下单页
 * @param {JumpToCheckOutParams} params - 参数选项
 * @property {Number} params.skuId - 商品skuId
 * @property {Number} params.num - 商品数量
 */

export const jumpToCheckOutSync = (params: JumpToCheckOutParams): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.jumpToCheckOut({
      params: {
        wareId: params.skuId, //skuid
        wareNum: params.num, //商品数量
      },
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/**
 *
 * @description Ios咚咚客服跳转
 * @param {NavigateToNativeDongDongChatByIosParams} params - 参数选项
 * @property {Number||String} params.venderId - venderId
 * @property {Object} params.param - 跳转携带参数
 */

export const navigateToNativeDongDongChatByIosSync = (
  params: NavigateToNativeDongDongChatByIosParams,
): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.navigateToNative({
      dataParam: {
        url: "openapp.jdmobile://virtual",
        params: {
          category: "jump",
          des: "jd_dongdong_chat",
          venderId: params.venderId,
          param: params.param,
        },
      },
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/**
 *
 * @description //Android咚咚客服跳转
 * @param {NavigateToNativeDongDongChatByAndroidParams} params - 参数选项
 * @property {Number||String} params.venderId - venderId
 * @property {Number||String} params.shopId -//商家id
 * @property {Number} params.customer_type - //0京东1微信
 * @property {Object} params.param - 跳转携带参数
 */

export const navigateToNativeDongDongChatByAndroidSync = (
  params: NavigateToNativeDongDongChatByAndroidParams,
): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.navigateToNative({
      dataParam: {
        url: "openapp.jdmobile://virtual",
        params: {
          category: "jump",
          des: "im",
          from: "com.jd.start.dd.entryask",
          customer_type: params.customer_type, //0京东1微信
          shopId: params.shopId, //商家id
          venderId: params.venderId, //同上
          param: params.param,
        },
      },
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/**
 *
 * @description // 京东入群
 * @param {NavigateToNativeDongDongGroupChatParams} params - 参数选项
 * @property {Number||String} params.groupId - 群groupId
 * @property {Object} params.param - 跳转携带参数
 */

export const navigateToNativeDongDongGroupChatSync = (
  params: NavigateToNativeDongDongGroupChatParams,
): Promise<any> => {
  return new Promise((resolve, reject) => {
    jd.navigateToNative({
      dataParam: {
        url: "openapp.jdmobile://virtual",
        params: {
          category: "jump",
          sourceValue: "",
          sourceType: "",
          des: "dongdong_group_chat",
          groupId: params.groupId,
          source: "2",
          param: params.param,
        },
      },
      success: res => {
        resolve(res);
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

/**
 *
 * @description // 跳转入会
 * @param {NavigateToNativeJoinMemberParams} params - 参数选项
 * @property {String} params.url - 入会链接
 * @property {Object} params.param - 跳转携带参数
 */

export const jdJump = (url: string) => {
  (jd as unknown as jd).navigateToNative({
    dataParam: {
      url: "openapp.jdmobile://virtual",
      params: {
        category: "jump",
        url: url, //用接口返回的url
        des: "m",
        param: {},
      },
    },
  });
};

/*
    @name: getServerTime
    @author: zhangzw
    @date: 2024-01-22 09:29:40
    @LastEditors:zhangzw
    @LastEditTime:2024-01-22 09:29:40
    @params:
    @return:当前时间戳
    @description: 获取服务器时间
*/
export const jdLogin = (): Promise<string> => {
  return new Promise((resolve, reject) => {
    (jd as unknown as jd).requestIsvToken({
      url: "https://midea-guanmei-isv.isvjcloud.com", //此处必须使用京东分配的域名才能调用成功
      id: "",
      success: res => {
        if (Object.prototype.toString.call(res) == "[object String]") {
          res = JSON.parse(res);
          resolve(res.data);
        } else if (Object.prototype.toString.call(res.token) == "[object Object]") {
          resolve(res.token.data);
        } else {
          resolve(res.token);
        }
      },
      fail: res => {
        reject(res);
      },
    });
  });
};

/**
 *
 * @description // 跳转入会
 * @param {NavigateToNativeJoinMemberParams} params - 参数选项
 * @property {String} params.url - 入会链接
 * @property {Object} params.param - 跳转携带参数
 */

export const jdCalendar = (params: { startDate: string; url: string }) => {
  const jumpStr = {
    des: "jdmp",
    params: {
      url: params.url,
    },
    srv: "",
  };
  return new Promise((resolve, reject) => {
    (jd as unknown as jd).addJDReminder({
      startDate: params.startDate,
      type: 3,
      jumpStr: JSON.stringify(jumpStr), // API调用时必须传JSON字符串
      success: function ({ uniqueId }) {
        resolve(uniqueId);
      },
      fail: function (err) {
        reject();
      },
    });
  });
};
